package in.muton.edushare.newentities.upgraded.singleInvite;

import in.muton.edushare.EduShareSession;
import in.muton.edushare.newentities.DeptUserCreator;
import in.muton.edushare.newentities.upgraded.InviteUtils;
import in.muton.edushare.processing.objects.CourseDataHandler;
import in.muton.edushare.wicket.models.CayenneList;

import java.util.ArrayList;
import java.util.List;

import org.apache.wicket.model.IModel;

import com.edushare.common.dao.EnrolmentsDAO;
import com.edushare.common.orm.ORMInterface;
import com.edushare.common.vo.CourseInstances;
import com.edushare.common.vo.Users;

public class CourseInvite implements SingleAudienceInvite {
	private static final long serialVersionUID = 9192457575418037830L;
	private IModel<CourseInstances> cInst;

	public CourseInvite(IModel<CourseInstances> cInst) {
		this.cInst = cInst;
	}

	public List<String> inviteUsers(int role, CayenneList<Users> userList,
			ORMInterface ormInterface) {
		List<String> statusList = new ArrayList<String>();
		EnrolmentsDAO eDAO = new EnrolmentsDAO(ormInterface);
		List<IModel<Users>> users = userList.getObject();
		for (IModel<Users> u : users) {
			statusList.add(eDAO.addUserFB(cInst.getObject(), u.getObject(),
					role, EduShareSession.get().getLoggedInUser()));
		}
		return statusList;
	}

	public List<String> inviteUsers(int role,
			List<CayenneList<Users>> userList, ORMInterface ormInterface) {
		List<String> strList = new ArrayList<String>();
		for (CayenneList<Users> u : userList) {
			strList.addAll(inviteUsers(role, u, ormInterface));
		}
		return strList;
	}

	public List<String> inviteUsers(int role, String[] userList,
			ORMInterface ormInterface) {
		List<String> statusString = new ArrayList<String>();
		EnrolmentsDAO eDAO = new EnrolmentsDAO(ormInterface);

		DeptUserCreator duc = new DeptUserCreator(EduShareSession.get()
				.getSessionORMInterface(), new CourseDataHandler(cInst)
				.getOwner(), InviteUtils.convertCourseRoleToDept(role));

		Users from = EduShareSession.get().getLoggedInUser();
		for (String u : userList) {
			Users userVO = InviteUtils.getUserByString(u, ormInterface);
			if (userVO != null) {
				statusString.add(eDAO.addUserFB(cInst.getObject(), userVO,
						role, from));
			} else {
				if (InviteUtils.isEmailId(u)) {
					duc.addUsersToDept(u);
					userVO = InviteUtils.getUserByString(u, ormInterface);
					if (userVO != null) {
						statusString.add(eDAO.addUserFB(cInst.getObject(),
								userVO, role, from));
					} else {
						statusString.add("Unable to invite user " + u
								+ " due to unknown error.");
					}
				} else {
					statusString.add("Unable to determine the type of " + u);
				}
			}
		}
		return statusString;
	}

}
